package cn.huolabao.tenant;

import cn.huolabao.model.SysUser;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Getter
@Setter
public class LeecheeTenantHandler implements TenantLineHandler {

    private LeecheeTenantProperties properties;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    public LeecheeTenantHandler(LeecheeTenantProperties properties) {
        this.properties = properties;
    }


    @Override
    public Expression getTenantId() {
        SysUser user = getUser();
        if (!ObjectUtils.isEmpty(user)) {
            return new LongValue(user.getTenantId());
        }
        return null;
    }

    @Override
    public String getTenantIdColumn() {
        return properties.getColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        SysUser user = getUser();
        if (ObjectUtils.isEmpty(user)) {
            return true;
        }
        String loginName = user.getUsername();
        if (properties.getAdmin().contains(loginName)) {
            return true;
        }
        boolean contains = properties.getSysTables().contains(tableName);
        boolean aNull = ObjectUtils.isEmpty(user.getTenantId());
        return (contains || aNull);
    }

    private SysUser getUser() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (ObjectUtils.isEmpty(header)) {
            return null;
        }
        return (SysUser) redisTemplate.opsForValue().get(header.replace("Bearer ", ""));
    }
}